package com.study.talk.ui.app.moment

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.PopupMenu
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.ImageOnly
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.study.talk.R
import com.study.talk.ui.adapter.ChooseImageGridAdapter
import com.study.talk.ui.app.base.BaseActivity
import com.study.talk.databinding.ActivityAddMomentBinding
import com.study.talk.utils.alert.AlertUtil
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.time.delay
import kotlinx.coroutines.withContext
import java.time.Duration

@AndroidEntryPoint
class AddMomentActivity : BaseActivity() {

    private val imageChooseLauncher: ActivityResultLauncher<PickVisualMediaRequest> =
        registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(9)) {
            if (it.isEmpty()) {
                AlertUtil.showCustomDialog(
                    this@AddMomentActivity,
                    "操作提醒",
                    "你没有选择任何照片，是打算发一个没有图片的动态吗?"
                ) { b ->
                    if (b) vm.changeImagesUri(mutableListOf())
                    else chooseImg()
                }
            } else {
                vm.changeImagesUri(it.toMutableList())
            }
        }

    private val vm: AddMomentViewModel by viewModels()

    private val binding: ActivityAddMomentBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_add_moment)
    }

    private val adapter: ChooseImageGridAdapter by lazy {
        ChooseImageGridAdapter(itemClick = itemClick, itemLongClick = itemLongClick)
    }

    //图片点击事件处理
    private val itemClick: (Int) -> Unit = { position ->
        vm.imagesUri.value?.let {
            if (vm.isChoose(position)) {
                AlertUtil.showCustomDialog(
                    this@AddMomentActivity,
                    "操作提醒",
                    "重新选择照片后当前已选择的和照片会被移除哦，确定要这么操作吗？"
                ) { b ->
                    if (b) chooseImg()
                }
            }
        }
    }

    //图片长按事件处理
    private val itemLongClick: (Int, View) -> Unit = { position, view ->
        if (!vm.isChoose(position)) {
            val popupMenu = PopupMenu(this@AddMomentActivity, view).apply {
                menuInflater.inflate(R.menu.delete, menu)
            }
            popupMenu.setOnMenuItemClickListener { item ->
                when (item.itemId) {
                    R.id.menu_delete -> vm.remove(position)  //删除照片
                }
                true
            }
            popupMenu.show()
        }
    }

    private val leave = {
        AlertUtil.showCustomDialog(
            this@AddMomentActivity, "退出提醒", "确认退出吗？内容不会被保存哦!"
        ) { b: Boolean ->
            if (b) finish()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.vm = vm
        binding.lifecycleOwner = this
        binding.addMomentToolbar.setNavigationOnClickListener { leave() }
        binding.addMomentGridView.adapter = adapter
        binding.addMomentGridView.layoutManager = GridLayoutManager(this, 3)

        vm.imagesUri.observe(this) {
            adapter.submitList(it)
        }

        vm.complete.observe(this) {
            lifecycleScope.launch(Dispatchers.IO){
                delay(Duration.ofSeconds(1))
                withContext(Dispatchers.Main){
                    finish()
                }
            }
        }

        //发布
        binding.addMomentBt.setOnClickListener {
            vm.submit()
        }
        chooseImg()
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            leave()
        }
        return false
    }


    private fun chooseImg() {
        imageChooseLauncher.launch(
            PickVisualMediaRequest.Builder().setMediaType(ImageOnly).build()
        )
    }
}